import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, message, Modal, Form, Input, Select, Switch, Row, Col, Tree, Popconfirm, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, BranchesOutlined, SearchOutlined, ReloadOutlined, FileOutlined, FolderOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import SearchForm, { SearchFieldConfig } from '@/components/SearchForm';
import DataTable, { PaginationConfig, ToolbarAction, BatchAction } from '@/components/DataTable';
import { 
  getCategoryList,
  getCategoryTree,
  createCategory,
  updateCategory,
  deleteCategory,
  batchUpdateCategoryStatus,
  getCategoryStatistics,
  type Category,
  type CategoryQueryParams,
  type CreateCategoryRequest,
  type UpdateCategoryRequest,
  type CategoryListResponse
} from '@/services/categories';

const { Option } = Select;
const { Search } = Input;

const Categories: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [categoryTree, setCategoryTree] = useState<Category[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [modalVisible, setModalVisible] = useState(false);
  const [treeModalVisible, setTreeModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [statistics, setStatistics] = useState<any>({});
  const [viewMode, setViewMode] = useState<'table' | 'tree'>('table');
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      name: 'keyword',
      type: 'input',
      placeholder: '类别名称/描述/别名',
      width: 200,
      prefix: <SearchOutlined />
    },
    {
      name: 'parent_id',
      type: 'select',
      placeholder: '选择父类别',
      width: 150,
      options: [
        { label: '根类别', value: 'null' }
      ]
    },
    {
      name: 'is_active',
      type: 'select',
      placeholder: '选择状态',
      width: 100,
      options: [
        { label: '启用', value: 'true' },
        { label: '禁用', value: 'false' }
      ]
    }
  ];

  // 表格列配置
  const columns: ColumnsType<Category> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '类别名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name: string, record: Category) => (
        <div className="flex items-center">
          {record.parent_id ? (
            <FileOutlined className="mr-2 text-blue-500" />
          ) : (
            <FolderOutlined className="mr-2 text-orange-500" />
          )}
          <span className="font-medium">{name}</span>
        </div>
      ),
    },
    {
      title: '别名',
      dataIndex: 'slug',
      key: 'slug',
      width: 150,
      render: (slug: string) => (
        <code className="bg-gray-100 px-2 py-1 rounded text-sm">{slug}</code>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (description: string) => (
        description ? (
          <Tooltip title={description} placement="topLeft">
            <span>{description}</span>
          </Tooltip>
        ) : (
          <span className="text-gray-400">暂无描述</span>
        )
      ),
    },
    {
      title: '父类别',
      dataIndex: 'parent_name',
      key: 'parent_name',
      width: 120,
      render: (parentName: string) => (
        parentName ? (
          <Tag color="blue">{parentName}</Tag>
        ) : (
          <Tag color="green">根类别</Tag>
        )
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort_order',
      key: 'sort_order',
      width: 80,
      sorter: (a: Category, b: Category) => a.sort_order - b.sort_order,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 100,
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'green' : 'red'} icon={isActive ? <CheckOutlined /> : <CloseOutlined />}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '子类别',
      dataIndex: 'children_count',
      key: 'children_count',
      width: 100,
      render: (count: number) => (
        <Tag color={count > 0 ? 'blue' : 'default'}>
          {count} 个
        </Tag>
      ),
    },
    {
      title: '商品数',
      dataIndex: 'products_count',
      key: 'products_count',
      width: 100,
      render: (count: number) => (
        <Tag color={count > 0 ? 'orange' : 'default'}>
          {count} 个
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 200,
      render: (record: Category) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确认删除"
              description={`确定要删除类别 "${record.name}" 吗？`}
              onConfirm={() => handleDelete(record.id)}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
                disabled={(record.children_count || 0) > 0 || (record.products_count || 0) > 0}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 获取类别列表
  const fetchData = async (page: number = currentPage, size: number = pageSize) => {
    try {
      setLoading(true);
      const searchValues = searchForm.getFieldsValue();
      
      const params: CategoryQueryParams = {
        page,
        limit: size,
        ...searchValues,
      };

      const response = await getCategoryList(params);
      
      if (response.data.success) {
        setCategories(response.data.data.items || []);
        setTotal(response.data.data.pagination.total);
        setCurrentPage(page);
        setPageSize(size);
      } else {
        message.error(response.data.message || '获取类别列表失败');
      }
    } catch (error) {
      console.error('获取类别列表失败:', error);
      message.error('获取类别列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取类别树
  const fetchCategoryTree = async () => {
    try {
      setLoading(true);
      const response = await getCategoryTree(true);
      if (response.data.success) {
        setCategoryTree(response.data.data);
      }
    } catch (error) {
      console.error('获取类别树失败:', error);
      message.error('获取类别树失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取统计信息
  const fetchStatistics = async () => {
    try {
      const response = await getCategoryStatistics();
      if (response.data.success) {
        setStatistics(response.data.data);
      }
    } catch (error) {
      console.error('获取统计信息失败:', error);
    }
  };

  // 转换树形数据为Antd Tree组件格式
  const convertToTreeData = (categories: Category[]): any[] => {
    return categories.map(category => ({
      key: category.id,
      title: (
        <div className="flex items-center justify-between w-full">
          <div className="flex items-center">
            {category.children && category.children.length > 0 ? (
              <FolderOutlined className="mr-2 text-orange-500" />
            ) : (
              <FileOutlined className="mr-2 text-blue-500" />
            )}
            <span className="font-medium">{category.name}</span>
            <code className="bg-gray-100 px-1 py-0.5 rounded text-xs ml-2">{category.slug}</code>
                         <Tag 
               color={category.is_active ? 'green' : 'red'} 
               className="ml-2"
             >
               {category.is_active ? '启用' : '禁用'}
             </Tag>
           </div>
           <div className="flex items-center space-x-1">
             <Tag color="blue">{category.products_count || 0}商品</Tag>
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleEdit(category);
              }}
            />
                         <Popconfirm
               title="确认删除"
               description={`确定要删除类别 "${category.name}" 吗？`}
               onConfirm={(e) => {
                 e?.stopPropagation();
                 handleDelete(category.id);
               }}
               okText="确认"
               cancelText="取消"
             >
               <Button
                 type="link"
                 size="small"
                 danger
                 icon={<DeleteOutlined />}
                 disabled={(category.children_count || 0) > 0 || (category.products_count || 0) > 0}
                 onClick={(e) => e.stopPropagation()}
               />
             </Popconfirm>
          </div>
        </div>
      ),
      children: category.children ? convertToTreeData(category.children) : undefined,
    }));
  };

  // 事件处理
  const handleSearch = () => {
    fetchData(1, pageSize);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchData(1, pageSize);
  };

  const handleTableChange = (pagination: any) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  const handleAdd = () => {
    setEditingCategory(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: Category) => {
    setEditingCategory(record);
    form.setFieldsValue({
      ...record,
      is_active: record.is_active,
    });
    setModalVisible(true);
  };

  const handleView = (record: Category) => {
    Modal.info({
      title: `类别详情: ${record.name}`,
      content: (
        <div className="space-y-3">
          <div><strong>ID:</strong> {record.id}</div>
          <div><strong>名称:</strong> {record.name}</div>
          <div><strong>别名:</strong> <code>{record.slug}</code></div>
          <div><strong>描述:</strong> {record.description || '暂无描述'}</div>
          <div><strong>父类别:</strong> {record.parent_name || '根类别'}</div>
          <div><strong>排序:</strong> {record.sort_order}</div>
          <div><strong>状态:</strong> 
            <Tag color={record.is_active ? 'green' : 'red'} className="ml-2">
              {record.is_active ? '启用' : '禁用'}
            </Tag>
          </div>
          <div><strong>子类别数:</strong> {record.children_count || 0}</div>
          <div><strong>商品数:</strong> {record.products_count || 0}</div>
          <div><strong>创建时间:</strong> {new Date(record.created_at).toLocaleString()}</div>
          <div><strong>更新时间:</strong> {new Date(record.updated_at).toLocaleString()}</div>
          {record.meta_title && <div><strong>SEO标题:</strong> {record.meta_title}</div>}
          {record.meta_description && <div><strong>SEO描述:</strong> {record.meta_description}</div>}
        </div>
      ),
      width: 600,
    });
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await deleteCategory(id);
      if (response.data.success) {
        message.success('删除成功');
        fetchData();
        fetchCategoryTree();
        fetchStatistics();
      } else {
        message.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      const categoryData: CreateCategoryRequest | UpdateCategoryRequest = {
        ...values,
        is_active: values.is_active !== undefined ? values.is_active : true,
      };

      if (editingCategory) {
        const response = await updateCategory(editingCategory.id, categoryData);
        if (response.data.success) {
          message.success('更新成功');
        } else {
          message.error(response.data.message || '更新失败');
          return;
        }
      } else {
        const response = await createCategory(categoryData as CreateCategoryRequest);
        if (response.data.success) {
          message.success('创建成功');
        } else {
          message.error(response.data.message || '创建失败');
          return;
        }
      }
      
      setModalVisible(false);
      fetchData();
      fetchCategoryTree();
      fetchStatistics();
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    }
  };

  // 批量操作
  const handleBatchUpdateStatus = async (isActive: boolean) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要操作的类别');
      return;
    }

    try {
      const response = await batchUpdateCategoryStatus(
        selectedRowKeys as number[], 
        isActive
      );
      if (response.data.success) {
        message.success(`批量${isActive ? '启用' : '禁用'}成功`);
        setSelectedRowKeys([]);
        fetchData();
        fetchCategoryTree();
      } else {
        message.error(response.data.message || '批量操作失败');
      }
    } catch (error) {
      console.error('批量操作失败:', error);
      message.error('批量操作失败');
    }
  };

  // 生成父类别选项
  const generateParentOptions = (categories: Category[], level = 0): JSX.Element[] => {
    let options: JSX.Element[] = [];
    
    categories.forEach(category => {
      // 如果是编辑模式，排除自己和自己的子类别
      if (editingCategory && (category.id === editingCategory.id)) {
        return;
      }
      
      const prefix = '　'.repeat(level);
      options.push(
        <Option key={category.id} value={category.id}>
          {prefix}{category.name}
        </Option>
      );
      
      if (category.children && category.children.length > 0) {
        options = options.concat(generateParentOptions(category.children, level + 1));
      }
    });
    
    return options;
  };

  useEffect(() => {
    fetchData();
    fetchCategoryTree();
    fetchStatistics();
  }, []);

  // 工具栏操作配置
  const toolbarActions: ToolbarAction[] = [
    {
      key: 'create',
      label: '添加类别',
      type: 'primary',
      icon: <PlusOutlined />,
      onClick: handleAdd
    },
    {
      key: 'tableView',
      label: '表格视图',
      type: viewMode === 'table' ? 'primary' : 'default',
      onClick: () => setViewMode('table')
    },
    {
      key: 'treeView', 
      label: '树形视图',
      type: viewMode === 'tree' ? 'primary' : 'default',
      onClick: () => setViewMode('tree')
    }
  ];

  // 批量操作配置
  const batchActions: BatchAction[] = [
    {
      key: 'active',
      label: '批量启用',
      onClick: () => handleBatchUpdateStatus(true),
    },
    {
      key: 'inactive',
      label: '批量禁用',
      onClick: () => handleBatchUpdateStatus(false),
    },
  ];

  // 分页配置
  const paginationConfig: PaginationConfig = {
    current: currentPage,
    pageSize: pageSize,
    total: total,
    showTotal: (total: number) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: handleTableChange,
  };

  // 行选择配置
  const rowSelectionConfig = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  return (
    <div className="space-y-6">
      {/* 搜索区域 */}
      <SearchForm
        fields={searchFields}
        form={searchForm}
        onSearch={handleSearch}
        onReset={handleReset}
        loading={loading}
      />

      {/* 内容区域 */}
      {viewMode === 'table' ? (
        /* 类别列表 */
        <DataTable<Category>
          title="类别列表"
          columns={columns}
          dataSource={categories}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          rowSelection={rowSelectionConfig}
          toolbarActions={toolbarActions}
          batchActions={batchActions}
          scroll={{ x: 1200 }}
        />
      ) : (
        /* 树形视图 */
        <Card title="类别树形结构">
          <Tree
            treeData={convertToTreeData(categoryTree)}
            defaultExpandAll
            showLine={{ showLeafIcon: false }}
          />
        </Card>
      )}

      {/* 编辑模态框 */}
      <Modal
        title={editingCategory ? '编辑类别' : '添加类别'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={700}
        maskClosable={false}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="类别名称"
                rules={[{ required: true, message: '请输入类别名称' }]}
              >
                <Input placeholder="请输入类别名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="slug"
                label="别名"
                rules={[{ required: true, message: '请输入别名' }]}
              >
                <Input placeholder="请输入别名" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入类别描述" rows={3} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="parent_id"
                label="父类别"
              >
                <Select placeholder="请选择父类别" allowClear>
                  <Option value={null}>根类别</Option>
                  {generateParentOptions(categoryTree)}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="sort_order"
                label="排序"
              >
                <Input type="number" placeholder="排序值，数字越小越靠前" min={0} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="image"
                label="图片URL"
              >
                <Input placeholder="请输入图片URL" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="icon"
                label="图标"
              >
                <Input placeholder="请输入图标class或URL" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="meta_title"
                label="SEO标题"
              >
                <Input placeholder="请输入SEO标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="is_active"
                label="状态"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="meta_description"
            label="SEO描述"
          >
            <Input.TextArea placeholder="请输入SEO描述" rows={2} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Categories; 